function sequence = bciGenerateFlashSequence(nSeq,nObj)

% this function generates a randomized flash sequence 

if nargin ==0,
    nSeq = 5;
end
if nargin<2,
    nObj = 6;
end
nFEpT = max(nObj,6); % a minimum of 6 flash events per trial is required 

seqType=2;
switch seqType,
    case 1,
        sequence = [ 1 1 0 0; ...
            0 0 1 0; ...
            1 0 0 1; ...
            0 1 0 0; ...
            0 0 1 1; ...
            1 0 0 0; ...
            0 1 1 0; ...
            0 0 0 1; ...
            1 0 1 0; ...
            0 1 0 1];
        minDist = 1;
        randseq = zeros(size(sequence));
    validSequenceFound = false;
    count=0;
    while ~validSequenceFound && count <5,
        count = count +1;
        sequence = randomizeSequenceRecursive(sequence,randseq,1:size(sequence,1), 1,minDist,GetSecs+1);
        validSequenceFound = all(sum(sequence,2)>0);
    end
    case 2,
        sequence = repmat(eye(nFEpT),nSeq,1); %nSeq sequences of single object flashes
        lastFlash = zeros(1,nFEpT);
        % randomize
        for k=1:nSeq,
            isDist = false;
            while ~isDist,
               randIdx = randperm(nFEpT);
               randSeq = sequence(randIdx + (k-1)*nFEpT,:);
               isDist = all(lastFlash~=randSeq(1,:)|randSeq(1,:)==0);
            end
            sequence((1:nFEpT) + (k-1)*nFEpT,:)= randSeq;
            lastFlash = randSeq(end,:);
        end
end
if any(sum(sequence,2)==0),
    error('Not able to determine valid flash sequence.');
end
if nObj<nFEpT, % reset pseudo target flashes
    sequence(:,nObj+1:nFEpT)=0;
end

function [randseq isValid leftSeqIdx] = randomizeSequenceRecursive(sequence, randseq, leftSeqIdx,depth,minDist,timeout)
% fprintf('%i ',depth);
if isempty(leftSeqIdx) || GetSecs>timeout, % terminate
    isValid = true;
    return;
end

isValid = false;
nIdx=randperm(length(leftSeqIdx));

for k=1:length(nIdx)
    if depth ==1 || ~any(sequence(leftSeqIdx(nIdx(k)),:)+ sum(randseq(depth-(1:min(minDist,depth-1)),:),1)>1), % valid condition
        randseq(depth,:)=sequence(leftSeqIdx(nIdx(k)),:); 
        [randseq isValid curLeftSeqIdx] = randomizeSequenceRecursive(sequence,randseq,...
                                        setdiff(leftSeqIdx,leftSeqIdx(nIdx(k))), depth+1,minDist,timeout);
        if isValid,
            leftSeqIdx = curLeftSeqIdx;
            return;
        end
    end
end